#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<list>
using namespace std;


struct ListNode {
    int val;
    struct ListNode* next;

    ListNode(int x)
        : val(x)
        , next(nullptr)
    {}
};
 

ListNode* deleteDuplicates(ListNode* head) {
    if (head == nullptr)
        return nullptr;
    ListNode* h = new ListNode(-1);
    h->next = head;
    ListNode* tail = head;
    int flag = 0;
    while (tail->next)
    {
        if (tail->val == tail->next->val)
        {
            ListNode* tmp = tail->next;
            tail->next = tmp->next;
            delete tmp;
            flag = 1;
        }
        else
        {
            if (flag == 1)
            {
                if (tail == h->next)
                {
                    h->next = tail->next;
                    delete tail;
                    tail = h->next;
                }
                else
                {
                    ListNode* tmp = tail->next;
                    delete tail;
                    tail = tmp;
                }
                flag = 0;
            }
            else
                tail = tail->next;
        }
    }
    if (flag == 1)
    {
        ListNode* p = h;
        while (p->next != tail)
        {
            p = p->next;
        }
        p->next = tail->next;
        delete tail;
    }
    return h->next;
}

int main()
{
    ListNode* h = new ListNode(-1);
    ListNode* p1 = new ListNode(1);
    ListNode* p2 = new ListNode(1);
    ListNode* p3 = new ListNode(2);

    h->next = p1;
    p1->next = p2;
    p2->next = p3;
    p3->next = nullptr;
    deleteDuplicates(p1);

    return 0;
}